package com.csu.petstore.service.Impl;

import com.csu.petstore.mapper.AccountMapper;
import com.csu.petstore.mapper.ProfileMapper;
import com.csu.petstore.pojo.Account;
import com.csu.petstore.pojo.Profile;
import com.csu.petstore.pojo.User;
import com.csu.petstore.service.AccountAndProfileService;
import com.csu.petstore.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class AccountAndProfileServiceImpl implements AccountAndProfileService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private ProfileMapper profileMapper;
    @Autowired
    private UserService userService;

    @Override
    public String ExceptionHandlerOfAccount(BindingResult bindingResult, Account account) {
        String errorMsg="";
        if (bindingResult.hasErrors()){
            List<String> errorMessages = bindingResult.getAllErrors().stream()
                    .map(error -> ((FieldError) error).getDefaultMessage())
                    .collect(Collectors.toList());
            errorMsg = String.join(", ", errorMessages);
        }
        else if (!account.getPassword().equals(account.getRepeatpassword())){
            errorMsg +="两次密码不一致!";
        }
        else if (userService.isExistUser(account.getUserid())){
            errorMsg +="用户名已存在！";
        }
        System.out.println(errorMsg);
        return errorMsg;
    }

    @Override
    public void setAccountAndProfileMsg(Account account, Profile profile) {
        int CountOfAccount = accountMapper.insert(account);
        int CountOfProfile = profileMapper.insert(profile);
        User user = new User(account.getUserid(),account.getPassword());
        userService.insertUser(user);
    }

    @Override
    public Account getAccountByUserId(String userid) {
        return accountMapper.selectById(userid);
    }

    @Override
    public Profile getProfileBYUserId(String userid) {
        return profileMapper.selectById(userid);
    }

    @Override
    public void deleteByUserId(String userid) {
        accountMapper.deleteById(userid);
        profileMapper.deleteById(userid);

    }
}
